﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using SaiLing.Common;
using Microsoft.AspNetCore.Mvc;

namespace SaiLing.SingleSignOn.Application.Core.Authorizations
{
    public class WebAuthorizeHandler : AuthorizationHandler<WebAuthorizationRequirement>
    {
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, WebAuthorizationRequirement requirement)
        {
            var filterContext = (AuthorizationFilterContext)context.Resource;
            var user = await AuthorizationHelper.Get();
            if (user == null)
            {
                requirement.IsAuth = false;
                var result = new ApiJsonResultData().RunWithTry(x =>
                {
                    x.Code = 401;
                    x.AddErrorMessage("未登录或未授权");
                });
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.Result = new JsonResult(result);
            }
            else
            {
                requirement.IsAuth = true;
            }
            context.Succeed(requirement);
        }
    }
}
